// 认证相关路由配置

const Router = require('@koa/router');
const mongoose = require('mongoose');
const GoodClassifyModel = mongoose.model('GoodClassify');

const router = new Router({
  prefix: '/good-classify',
});

// 注册 接口
router.get('/list', async (ctx) => {
  console.log('--> 调用接口 get /good-classify/list');
  let { page, size } = ctx.query;
  page = Number(page);
  size = Number(size);
  const list = await GoodClassifyModel.find()
    .sort({ _id: -1 })
    .skip((page - 1) * size)
    .limit(size)
    .exec();
  const total = await GoodClassifyModel.find().countDocuments().exec();
  ctx.body = {
    msg: `获取分类列表成功`,
    code: 1,
    data: {
      list,
      total,
    },
  };
});

// 添加分类 接口
router.post('/add', async (ctx) => {
  console.log('--> 调用接口 post /good-classify/add');
  const { title } = ctx.request.body;
  if (title === '') {
    ctx.body = { msg: '分类名称不能为空字符串', code: 0, data: null };
    return;
  }
  const one = await GoodClassifyModel.findOne({ title }).exec();
  if (one) {
    ctx.body = { msg: '分类已存在', code: 0, data: null };
    return;
  }
  const classify = new GoodClassifyModel({ title });
  await classify.save();
  ctx.body = {
    msg: '添加商品分类成功',
    code: 1,
    data: null,
  };
});

// 删除分类 接口
router.delete('/:id', async (ctx) => {
  console.log('--> 调用接口 post /good-classify/add');
  const { id } = ctx.params;
  console.log(id);
  const delMsg = await GoodClassifyModel.deleteOne({ _id: id }).exec();
  ctx.body = {
    msg: '删除商品分类成功',
    code: 1,
    data: delMsg,
  };
});

// 修改分类 接口
router.post('/update', async (ctx) => {
  console.log('--> 调用接口 post /good-classify/add');
  const { id, title } = ctx.request.body;
  const one = await GoodClassifyModel.findOne({ _id: id }).exec();
  one.title = title;
  await one.save();
  ctx.body = {
    msg: '修改分类名称成功',
    code: 1,
    data: null,
  };
});

module.exports = router;
